package edu.ncst.baseweb.service.impl.borrow;

import cn.wintersun.basecommon.common.Result;
import edu.ncst.baseweb.dao.BorrowRecord;
import edu.ncst.baseweb.dao.User;
import edu.ncst.baseweb.dao.equ.Equ;
import edu.ncst.baseweb.dto.JwtUser;
import edu.ncst.baseweb.mapper.BorrowRecordMapper;
import edu.ncst.baseweb.mapper.EquClassMapper;
import edu.ncst.baseweb.mapper.EquMapper;
import edu.ncst.baseweb.mapper.UserMapper;
import edu.ncst.baseweb.service.intrer.borrow.BorrowService;
import edu.ncst.baseweb.utils.GetUserinfoUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class BorrowServiceImpl implements BorrowService {
    @Autowired private EquMapper equMapper;

    @Autowired private UserMapper userMapper;

    @Autowired private EquClassMapper equClassMapper;

    @Autowired private BorrowRecordMapper borrowRecordMapper;

    @Autowired
    private GetUserinfoUtil getUserinfoUtil;


    public Result<IPage<Equ>> list(Equ equ){
        QueryWrapper<Equ> queryWrapper = Wrappers.query();
        //设备名称查询
        if(StringUtils.isNotEmpty(equ.getName())){
            queryWrapper.like(Equ.COL_NAME,equ.getName());
        }

        //在库中且没报废
        queryWrapper.eq(Equ.COL_STATE, "在库中");
        queryWrapper.eq(Equ.COL_SCRAP, "0");
        //创建页数
        Page<Equ> userPage = new Page<>(equ.getCurrent(), equ.getPageSize());
        Page<Equ> equPage = equMapper.selectPage(userPage, queryWrapper);

        List<Equ> records = equPage.getRecords();
        for (Equ record : records) {
            //record.setClassName(className);
        }

        return Result.ok(equPage);
    }
    public Result<Object> borrow(Equ equ){
        BorrowRecord borrowRecord = new BorrowRecord();

        //将借用的设备改为待审核的状态
        equMapper.updateEquStateById(equ.getId(),"待审核");

        //获取当前登录账号的id
        JwtUser jwtUser = getUserinfoUtil.getUser();
        QueryWrapper<User> queryUser = Wrappers.query();
        queryUser.eq("USER_ACCOUNT",jwtUser.getUsername());
        User user = userMapper.selectOne(queryUser);
        borrowRecord.setUserId(user.getId());
        //获取设备id
        borrowRecord.setEquId(equ.getId());
        borrowRecord.setEquName(equ.getName());
        //当前状态审核中
        borrowRecord.setState(0);
        borrowRecord.setApplyTime(new Date());

        borrowRecord.setText(equ.getText());
        borrowRecord.setEtime(equ.getEtime());

        //插入数据
        borrowRecordMapper.insert(borrowRecord);


        //用户名称，设备名称，状态，四个时间，借用理由
        return Result.ok();
    }
}
